package com.web.exiaodao.remote.controller;

import com.web.exiaodao.business.entity.Address;
import com.web.exiaodao.remote.service.ApiAddressService;
import com.web.exiaodao.remote.service.ApiUserService;
import com.web.exiaodao.remote.vo.AddressVo;
import com.web.webstart.base.constant.XaConstant;
import com.web.webstart.base.controller.BaseController;
import com.web.webstart.base.exception.BusinessException;
import com.web.webstart.base.util.Validator;
import com.web.webstart.base.util.XaUtil;
import com.web.webstart.base.util.jpa.WebUitl;
import com.web.webstart.base.util.result.XaResult;
import com.wordnik.swagger.annotations.Api;
import com.wordnik.swagger.annotations.ApiOperation;
import com.wordnik.swagger.annotations.ApiParam;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * @author eason.zt
 * @version V1.0
 * @Title: ApiAddressController.java
 * @Package com.web.exiaodao.remote.controller
 * @Description: 收货地址信息接口
 * @date 2015年3月23日 下午1:00:00
 */
@Api(value = "Address", description = "收货地址接口", position = 10)
@Controller
@RequestMapping("/api/address")
public class ApiAddressController extends BaseController {

    private static final Logger LOGGER = Logger.getLogger(ApiAddressController.class);

    @Autowired
    private ApiUserService userService;
    @Autowired
    private ApiAddressService addressService;

    /**
     * @return
     * @Title: findAddressList
     * @Description: 查询所有收货地址信息
     */
    @ApiOperation(value = "查询所有收货地址", notes = "查询所有收货地址信息,当返回的code=1时，取出object进行显示,存放为数组对象")
    @ResponseBody
    @RequestMapping(value = "findAddressList", method = RequestMethod.POST)
    public XaResult<List<AddressVo>> findAddressList(
            @ApiParam("用户Id,字段名:userId") @RequestParam(value = "userId") Long userId
    ) throws BusinessException {
        XaResult<List<AddressVo>> xr = new XaResult<>();
        if (XaUtil.isEmpty(userId)) {
            xr.error("用户Id不能为空！");
            return xr;
        }
        if (XaUtil.isEmpty(userService.validUserId(userId + ""))) {
            xr.error("用户Id不存在！");
            return xr;
        }
        Pageable pageable = WebUitl.buildPageRequest(0, Integer.MAX_VALUE, "[{property:'createTime',direction:'DESC'}]");
        Map<String, Object> filterParams = WebUitl.getParametersStartingWith("{'search_EQ_userId':'" + userId + "'}", "search_");
        return addressService.findListEQStatusByFilter(XaConstant.Status.valid, filterParams, pageable);
    }

    /**
     * @param modelId
     * @return
     * @Title: findAddressById
     * @Description: 根据ID查找单条实体
     */
    @ApiOperation(value = "根据tId查询收货地址", notes = "查询收货地址详细信息,当返回的code=1时，取出object进行显示,存放为单体对象")
    @ResponseBody
    @RequestMapping(value = "findAddressById", method = RequestMethod.POST)
    public XaResult<AddressVo> findAddressById(
            @ApiParam("编号,字段名:modelId,必填") @RequestParam(value = "modelId") Long modelId
    ) throws BusinessException {
        return addressService.findOne(modelId);
    }

    /**
     * @param userId //@param model
     * @return
     * @Title: save
     * @Description: 新增一条实体
     */
    @ApiOperation(value = "新增收货地址", notes = "供前端前期填充数据测试使用,上线后删除;新增收货地址,当返回的code=1时，保存成功后object返回对象")
    @ResponseBody
    @RequestMapping(value = "saveAddress", method = RequestMethod.POST)
    public XaResult<AddressVo> saveAddress(
            @ApiParam("用户Id,字段名:userId") @RequestParam(value = "userId") Long userId,
            @ApiParam("收货人,字段名:consigneeName") @RequestParam(value = "consigneeName") String consigneeName,
            @ApiParam("手机号,字段名:mobile") @RequestParam(value = "mobile") String mobile,
            @ApiParam("省份,字段名:province") @RequestParam(value = "province") String province,
            @ApiParam("城市,字段名:city") @RequestParam(value = "city") String city,
            @ApiParam("区域,字段名:area") @RequestParam(value = "area") String area,
            @ApiParam("详细地址,字段名:detailAddress") @RequestParam(value = "detailAddress") String detailAddress,
            @ApiParam("是否默认,字段名:isDefault,可选,默认0") @RequestParam(value = "isDefault", required = false, defaultValue = "0") Integer isDefault,
            @ApiParam("邮政编码,字段名:postcode") @RequestParam(value = "postcode") String postcode,
            HttpServletRequest request
    ) throws BusinessException {
        XaResult<AddressVo> xr = new XaResult<AddressVo>();
        if (XaUtil.isEmpty(userId)) {
            xr.error("用户Id不能为空！");
            return xr;
        }
        if (XaUtil.isEmpty(userService.validUserId(userId + ""))) {
            xr.error("用户Id不存在！");
            return xr;
        }
        if (XaUtil.isEmpty(consigneeName)) {
            xr.error("收货人不能为空！");
            return xr;
        }
        if (XaUtil.isEmpty(mobile)) {
            xr.error("手机号不能为空！");
            return xr;
        }
        if (XaUtil.isEmpty(province)) {
            xr.error("省份不能为空！");
            return xr;
        }
        if (XaUtil.isEmpty(city)) {
            xr.error("城市不能为空！");
            return xr;
        }
        if (XaUtil.isEmpty(area)) {
            xr.error("区域不能为空！");
            return xr;
        }
        if (XaUtil.isEmpty(detailAddress)) {
            xr.error("详细地址不能为空！");
            return xr;
        }
        if (XaUtil.isEmpty(isDefault)) {
            xr.error("是否默认不能为空！");
            return xr;
        }
        if (!Validator.isMobile(mobile)) {
            xr.error("请输入正确的手机号！");
            return xr;
        }
        if (!(isDefault == 0 || isDefault == 1)) {
            xr.error("输入的是否默认非法！");
            return xr;
        }
        if (detailAddress.length() > 50) {
            xr.error("详细地址不能超过50个字");
            return xr;
        }
        Address model = new Address();
        model.setConsigneeName(consigneeName);
        model.setMobile(mobile);
        model.setProvince(province);
        model.setCity(city);
        model.setArea(area);
        model.setDetailAddress(detailAddress);
        model.setUserId(userId);
        model.setIsDefault(isDefault);
        model.setPostcode(postcode);
        return addressService.createModel(model);
    }

    /**
     * @param userId //@param model
     * @return
     * @Title:
     * @Description: 修改一条实体
     */
    @ApiOperation(value = "修改收货地址", notes = "修改收货地址,当返回的code=1时，保存成功后object返回对象")
    @ResponseBody
    @RequestMapping(value = "updateAddress", method = RequestMethod.POST)
    public XaResult<AddressVo> updateAddress(
            @ApiParam("唯一编号,字段名:tId") @RequestParam(value = "tId") Long tId,
            @ApiParam("用户Id,字段名:userId") @RequestParam(value = "userId") Long userId,
            @ApiParam("收货人,字段名:consigneeName") @RequestParam(value = "consigneeName", required = false) String consigneeName,
            @ApiParam("手机号,字段名:mobile") @RequestParam(value = "mobile", required = false) String mobile,
            @ApiParam("省份,字段名:province") @RequestParam(value = "province", required = false) String province,
            @ApiParam("城市,字段名:city") @RequestParam(value = "city", required = false) String city,
            @ApiParam("区域,字段名:area") @RequestParam(value = "area", required = false) String area,
            @ApiParam("详细地址,字段名:detailAddress") @RequestParam(value = "detailAddress", required = false) String detailAddress,
            @ApiParam("是否默认,字段名:isDefault") @RequestParam(value = "isDefault", required = false) Integer isDefault,
            @ApiParam("邮政编码,字段名:postcode") @RequestParam(value = "postcode", required = false) String postcode,
            HttpServletRequest request
    ) throws BusinessException {
        XaResult<AddressVo> xr = new XaResult<AddressVo>();
        if (XaUtil.isEmpty(tId)) {
            xr.error("id不能为空！");
            return xr;
        }
        if (XaUtil.isNotEmpty(mobile)) {
            if (!Validator.isMobile(mobile)) {
                xr.error("请输入正确的手机号！");
                return xr;
            }
        }
        if (XaUtil.isNotEmpty(isDefault)) {
            if (!(isDefault == 0 || isDefault == 1)) {
                xr.error("输入的是否默认非法！");
                return xr;
            }
        }
        if (XaUtil.isNotEmpty(detailAddress)) {
            if (detailAddress.length() > 50) {
                xr.error("详细地址不能超过50个字");
                return xr;
            }
        }

        //------------------------------------------------
        //测试编码集合
        try {
            String encoding = request.getCharacterEncoding();
            request.setCharacterEncoding("UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        Map requestMap = request.getParameterMap();
        String str = "";
        try {
            str = new String(request.getParameter("detailAddress").getBytes("iso-8859-1"), "utf-8");
            //设置来过滤器啥都没有用,结果是tomcat的原因;  app都的,就是网友提交有问题
        } catch (Exception e) {
            e.printStackTrace();
        }
        //------------------------------------------------

        try {
            Address model = new Address();
            model.setConsigneeName(consigneeName);
            model.setMobile(mobile);
            model.setProvince(province);
            model.setCity(city);
            model.setArea(area);
            model.setDetailAddress(detailAddress);
            model.setUserId(userId);
            model.setIsDefault(isDefault);
            model.setPostcode(postcode);
            model.setId(tId);
            addressService.updateModel(model);
        } catch (Exception e) {
            if (e instanceof BusinessException) {
                xr.error(e.getMessage());
            } else  {
                xr.error(XaConstant.Message.error);
            }
            LOGGER.error(XaConstant.Message.error, new Throwable(e));
        }
        return xr;
    }

    /**
     * @param status 操作类型:-1锁定,0无效,1正常,2发布,3删除,默认删除操作
     * @return
     * @Title: operateAddressById
     * @Description: 操作一个实体状态, 根据status进行操作
     * //@param modelId
     */
    @ApiOperation(value = "根据ID修改收货地址状态", notes = "修改收货地址状态,当返回的code=1时，保存成功后object返回对象")
    @ResponseBody
    @RequestMapping(value = "operateAddressById", method = RequestMethod.POST)
    public XaResult<AddressVo> operateAddressById(
            HttpServletRequest request,
            @ApiParam("编号,字段名:modelIds,必填") @RequestParam(value = "modelId") String modelIds,
            @ApiParam("操作类型,字段名:status,-1锁定,0无效,1正常,2发布,3删除,选填,默认删除操作") @RequestParam(defaultValue = "3") Integer status
    ) throws BusinessException {
        XaResult<AddressVo> xr = new XaResult<AddressVo>();
        if (XaUtil.isEmpty(modelIds)) {
            xr.error("id不能为空！");
            return xr;
        }
        return addressService.multiOperate(modelIds, status);
    }

}

